package com.uduemc.jcms.backend.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.jcms.backend.BackendModule;
import com.uduemc.jcms.backend.component.BackendLoginForm;
import com.uduemc.jcms.backend.component.SiteLanguageForm;
import com.uduemc.jcms.backend.service.IBJcmsBackendUserService;
import com.uduemc.jcms.common.entity.Logo;
import com.uduemc.jcms.common.entity.SiteLanguage;
import com.uduemc.jcms.common.service.ILogoService;
import com.uduemc.jcms.common.service.ISiteLanguageService;
import com.uduemc.jcms.common.utils.JsonResult;

@Controller
@RequestMapping(BackendModule.BaseRequest)
public class BSiteController {

	@Autowired
	IBJcmsBackendUserService bjcmsBackendUserServiceImpl;

	@Autowired
	BackendLoginForm backendLoginForm;

	@Autowired
	SiteLanguageForm siteLanguageForm;

	@Autowired
	ISiteLanguageService siteLanguageServiceImpl;

	@Autowired
	ILogoService logoServiceImpl;

	@Autowired
	ObjectMapper objectMapper;

	// 网站Logo设置
	@GetMapping("/site/logo.html")
	public ModelAndView logo(ModelAndView model) throws JsonProcessingException {
		Logo logo = logoServiceImpl.createIfNotExists();
		model.addObject("logo", objectMapper.writeValueAsString(logo));
		model.setViewName(BackendModule.ModuleName + "/site/logo");
		return model;
	}

	@PostMapping("/site/save-logo.html")
	@ResponseBody
	public JsonResult saveLogo(@RequestParam("repertoryId") int repertoryId, @RequestParam("logoConfig") String logoConfig) {
		return logoServiceImpl.save(repertoryId, logoConfig);
	}

	// 站点语言列表，用于 easyui combobox
	@GetMapping("/site/site-list-for-combobox")
	@ResponseBody
	public Object siteListForCombobox() {
		List<SiteLanguage> siteLanguageList = siteLanguageServiceImpl.findAll();
		List<Map<String, Object>> result = new ArrayList<>();
		Map<String, Object> map = null;
		for (SiteLanguage siteLanguage : siteLanguageList) {
			map = new HashMap<>();
			map.put("id", siteLanguage.getLanguage().getId());
			map.put("name", siteLanguage.getLanguage().getName());
			result.add(map);
		}
		return result;
	}

}
